package com.ruolin.micro.gateway.server.discovery;

import com.ruolin.micro.gateway.server.constant.PropertiesConstant;
import com.ruolin.micro.gateway.server.utils.DubboServiceUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.nacos.NacosServiceDiscovery;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Set;

/**
 * dubbo service nacos ServiceDiscovery
 */

public class NacosServiceDiscoveryAdapter extends AbstractServiceDiscoveryAdapter implements EnvironmentAware {
    private  NacosServiceDiscovery nacosServiceDiscovery;
    private Environment environment;

    @PostConstruct
    public void init() throws Exception {
        initialize(URL.valueOf(environment.getProperty(PropertiesConstant.NACOS_SERVER_ADDR)));
    }

    @Override
    public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
        return nacosServiceDiscovery.getInstances(serviceName);
    }

    @Override
    public ServiceInstance getLocalInstance() {
        return null;
    }

    @Override
    public void initialize(URL registryURL) throws Exception {
        this.nacosServiceDiscovery = new NacosServiceDiscovery();
        try {
            nacosServiceDiscovery.initialize(registryURL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Set<String> getServices() {
        return DubboServiceUtils.filterDubboService(nacosServiceDiscovery.getServices());
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
